package service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Random;

import action.WechatAccessTokenApi;
import bean.Lucky;
import dao.LuckyDAOImpl;

public class LuckyService {

    public static final String GET_DEPOSIT_COUNT = "http://api.weixin.qq.com/card/code/getdepositcount";
    public static final String GET_DEPOSIT_DETAIL = "https://api.weixin.qq.com/card/get";
    public static final String UPDATE_DEPOSIT_INFO = "https://api.weixin.qq.com/card/update";
    public static final String UPDATE_DEPOSIT_COUNT = "https://api.weixin.qq.com/card/modifystock";
    public static final String BUILD_NEW_DEPOSIT = "https://api.weixin.qq.com/card/create";

    // 获奖数量
    public static int LUCKY_COUNTS[] = new int[4];
    // 是否已缓存
    public static boolean CACHED = false;

    public String accessToken = "";

    private static Random luckyRand = new Random(new Date().getTime());

    private WechatAccessTokenApi wechatAccessTokenApi;
    private LuckyDAOImpl luckyDAOImpl;
    private DepositService depositService;

    public void setLuckyDAOImpl(LuckyDAOImpl luckyDAOImpl) {
        this.luckyDAOImpl = luckyDAOImpl;
    }

    public void setWechatAccessTokenApi(WechatAccessTokenApi wechatAccessTokenApi) {
        this.wechatAccessTokenApi = wechatAccessTokenApi;
    }
    
    public void setDepositService(DepositService depositService) {
        this.depositService = depositService;
    }

    /**
     * 抽奖
     * 
     * @return 奖品等级
     * @see Lucky LEVEL_FIRST 0 一等奖 LEVEL_SECOND 1 二等奖 LEVEL_THIRD 2 三等奖
     *      LEVEL_THIRD 2 三等奖 LEVEL_OTHER 3 四等奖
     */
    public int draw(String openId) {

        synchronized (LUCKY_COUNTS) {
            if (!CACHED) {
                LUCKY_COUNTS = new int[4];
                LUCKY_COUNTS[Lucky.LEVEL_FIRST] = luckyDAOImpl
                        .getCountByLevel(Lucky.LEVEL_FIRST);
                LUCKY_COUNTS[Lucky.LEVEL_SECOND] = luckyDAOImpl
                        .getCountByLevel(Lucky.LEVEL_SECOND);
                LUCKY_COUNTS[Lucky.LEVEL_THIRD] = luckyDAOImpl
                        .getCountByLevel(Lucky.LEVEL_THIRD);
                CACHED = true;
            }
        }
        // 获取随机数
        int randomResult = luckyRand.nextInt(10000);
        // 根据此随机数，判定其所属等级（初步等级）
        int level = randomResult < 45 ? Lucky.LEVEL_FIRST
                : randomResult < 135 ? Lucky.LEVEL_SECOND : Lucky.LEVEL_THIRD;

        // 根据目前已得奖人数，判定具体所属等级
        synchronized (LUCKY_COUNTS) {
            // 确定具体所属等级
            level = determineLevel(level);
            // 更新缓存
            LUCKY_COUNTS[level] += 1;
        }
        //随机决定是10元优惠券还是20元优惠券
        int number = new Random().nextInt(10) + 1;
        int type = number<=5?0:1;
        System.out.println("随机数为："+number+" type="+type);
        
        // 存入数据库
        Lucky lucky = new Lucky(openId, level, new Timestamp(
                new Date().getTime()), Lucky.STATUS_DEFAULT, type);

        if(openId != "ol-ZLt9k_FArQx5fpP9svPCzjCGw") {
            luckyDAOImpl.save(lucky);
            
        }
       
        return level;
    }
   

    /**
     * 根据目前已得奖情况，判定奖项具体所属等级 策略如下： 如果level为0，即一等奖，若此时一等奖不满45人，则最终为一等奖；否则尝试分配为二等奖
     * 如果level为1，即二等奖，若此时二等奖不满90人，则最终为二等奖；否则为三等奖 如果level为2，或者其他情况，直接分配三等奖
     * 
     * @param level
     * @return
     */
    /*
     * private int determineLevel(int level) { if (level == Lucky.LEVEL_FIRST) {
     * if (LUCKY_COUNTS[level] < 45) { return level; } else { return
     * determineLevel(Lucky.LEVEL_SECOND); } } else if (level ==
     * Lucky.LEVEL_SECOND) { if (LUCKY_COUNTS[level] < 90) { return level; }
     * else { return Lucky.LEVEL_THIRD; } } else { return Lucky.LEVEL_THIRD; } }
     */
    private int determineLevel(int level) {
        if (level == Lucky.LEVEL_FIRST) {
            if (LUCKY_COUNTS[level] < 45) {
                return level;
            } else {
                return determineLevel(Lucky.LEVEL_SECOND);
            }
        } else if (level == Lucky.LEVEL_SECOND) {
            if (LUCKY_COUNTS[level] < 90) {
                return level;
            } else {
                return determineLevel(Lucky.LEVEL_THIRD);
            }
        } else if (level == Lucky.LEVEL_THIRD) {
            if (LUCKY_COUNTS[level] < Lucky.LEVEL_THIRD_COUNT ) {
//                System.out.println("剩余卡券数目少于5000，并且满足发放条件");
                return level;
            } else{
                System.out.println("不具备发放卡券的条件， return level 3 instead");
                return Lucky.LEVEL_OTHER;
            }
                
        } else
            return Lucky.LEVEL_OTHER;

    }

    /**
     * 根据openId获取抽奖记录
     * 
     * @param openId
     * @return
     */
    public Lucky getByOpenId(String openId) {
        if (openId == null) {
            return null;
        }
        List<Lucky> list = luckyDAOImpl.findByOpenId(openId);
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    /**
     * 是否已经抽过奖
     * 
     * @param openId
     * @return
     */
    public boolean hasDrawed(String openId) {
        return getByOpenId(openId) != null;
    }

    /**
     * 获取已经抽到的奖
     * 
     * @param openId
     * @return
     */
    public Lucky getDrawed(String openId) {
        return getByOpenId(openId);
    }

    /**
     * 修改状态
     * 
     * @param openId
     * @param status
     */
    public void updateStatus(String openId, int status) {
        luckyDAOImpl.updateStatusByOpenId(openId, status);
    }
    
    public int getType(String openId){
        return luckyDAOImpl.getTypeByOpenId(openId);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; ++i) {
            // new Thread(new TestThread(i)).start();
        }
    }

}

